package com.example.parkdemo.ping

import androidx.paging.PagingSource
import androidx.paging.PagingState

class RepoPagingSource(val apiService: ApiService) : PagingSource<Int, Item>() {
    override fun getRefreshKey(state: PagingState<Int, Item>): Int? {
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Item> {
        return try {
            //网络请求返回数据源
            val page = params.key ?: 1
            val pageSize = params.loadSize
            val repoResponse = apiService.getPagingDate(page, pageSize)
            val items = repoResponse.items

            val preKey = if (page > 1) page - 1 else null
            val nextKey = if (items.isNotEmpty()) page + 1 else null
            LoadResult.Page(items, preKey, nextKey)
        } catch (e: Exception) {
            //相当于failed,请求失败，保存错误信息
            LoadResult.Error(e)
        }
    }
}